local desc_threembkj_mode = [[
  # 抗金简介
  ___

  3个玩家（身份固定为忠，玩家不足人机补位）对抗3个人机（身份固定为反贼）。

  胜利条件：反贼全部阵亡且达到设定的挑战组。

  失败条件：主忠全部阵亡。

]]
-- local XlkjObj = require "packages/xlkj/XlkjObj"
local U = require "packages/utility/utility"
local MobileSelGenMuty = require "packages/lang/MobileSelGenMuty"
local LU = require "packages/lang/LUltiity"
local KJobj = require "packages/lang/KJobj"

--开启测试
local IStest
-- local IStest = "mouxusheng"
--下一轮战斗准备数据
local nextBattleData = {
  {
    xiandengnum = 0,
    getsameskills = {loyalist = {"kj_gongjue"}},
    deadthsing = {rebel = {0,0,1}},
  },
  {
    xiandengnum = 1,
    getcardnum = {rebel=6,loyalist=2},
    getshield = {rebel = 1},
    getsameskills = {rebel = {"rongzhuangSkill"}},
    deadthsing = {rebel = {0,0,1}},
    rongzhuangnum = {rebel = 2}
  },
  {
    xiandengnum = 1,
    getcardnum = {rebel=7,lord = 4,loyalist=4},
    getmaxhp = {rebel = 1},
    getshield = {rebel = 1},
    getsameskills = {rebel = {"rongzhuangSkill"}},
    deadthsing = {rebel = {0,0,1}},
    rongzhuangnum = {rebel = 2},
    bossgens = {"godzhangjiao","caojinyu","tenggongzhu","godganning","zerong","hulao2__godlvbu","ty__sunyi"}
  },
}
--关卡奖励
--关刀
local mb_guandao = fk.CreateTargetModSkill{
  name = "mb_guandao",
  residue_func = function(self, player, skill, scope)
    if player:hasSkill(self) and skill.trueName == "slash_skill"
      and scope == Player.HistoryPhase then
      return 2
    end
  end,
}
Fk:addSkill(mb_guandao)
Fk:loadTranslationTable{
  ["mb_guandao"] = "关刀",
  [":mb_guandao"] = "锁定技，出牌阶段你使用杀次数+2",
}
--多多益善
local mb_ddys = fk.CreateTriggerSkill{
  name = 'mb_ddys',
  anim_type = "drawcard",
  -- priority = 21,
  frequency = Skill.Compulsory,
  events = {fk.EventAcquireSkill},
  can_trigger = function(self, event, target, player, data)
    return player == target and data == self
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:drawCards(player,3,self.name)
    room:handleAddLoseSkills(player,"-"..self.name,nil,false)
  end,
}
Fk:addSkill(mb_ddys)
Fk:loadTranslationTable{
  ["mb_ddys"] = "多多益善",
  [":mb_ddys"] = "摸3张牌。",
}
--强身健体
local mb_qsjt = fk.CreateTriggerSkill{
  name = 'mb_qsjt',
  anim_type = "support",
  -- priority = 21,
  frequency = Skill.Compulsory,
  events = {fk.EventAcquireSkill},
  can_trigger = function(self, event, target, player, data)
    return player == target and data == self
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    -- room:changeMaxHp(player,1)
    room:setPlayerProperty(player, "maxHp", player.maxHp+1)
    room:handleAddLoseSkills(player,"-"..self.name,nil,false)
  end,
}
Fk:addSkill(mb_qsjt)
Fk:loadTranslationTable{
  ["mb_qsjt"] = "强身健体",
  [":mb_qsjt"] = "体力上限+1",
}
--坚固壁垒
local mb_jgbl = fk.CreateTriggerSkill{
  name = 'mb_jgbl',
  anim_type = "support",
  -- priority = 21,
  frequency = Skill.Compulsory,
  events = {fk.EventAcquireSkill},
  can_trigger = function(self, event, target, player, data)
    return player == target and data == self
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:changeShield(player,2)
    room:handleAddLoseSkills(player,"-"..self.name,nil,false)
  end,
}
Fk:addSkill(mb_jgbl)
Fk:loadTranslationTable{
  ["mb_jgbl"] = "江东铁壁",
  [":mb_jgbl"] = "护甲+2",
}
--妙手回春
local mb_mshc = fk.CreateTriggerSkill{
  name = 'mb_mshc',
  anim_type = "drawcard",
  -- priority = 21,
  frequency = Skill.Compulsory,
  events = {fk.EventAcquireSkill},
  can_trigger = function(self, event, target, player, data)
    return player == target and data == self
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:recover({
      who = player,
      num = 2,
      skillName = self.name
    })
    room:handleAddLoseSkills(player,"-"..self.name,nil,false)
  end,
}
Fk:addSkill(mb_mshc)
Fk:loadTranslationTable{
  ["mb_mshc"] = "妙手回春",
  [":mb_mshc"] = "回复2点体力",
}
--脱胎换骨
local mb_tthg = fk.CreateTriggerSkill{
  name = 'mb_tthg',
  anim_type = "drawcard",
  -- priority = 21,
  frequency = Skill.Compulsory,
  events = {fk.EventAcquireSkill},
  can_trigger = function(self, event, target, player, data)
    return player == target and data == self and player.id > 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local genname = player.originskin or player.general 
    local gen = Fk.generals[genname]
    local generalskills = gen:getSkillNameList()
    if #generalskills > 0 then
      local loseskills = ""
      for _,s in ipairs(generalskills) do
        loseskills = loseskills.."-"..s.."|"
      end
      room:handleAddLoseSkills(player, loseskills, nil, false)
    end
    local general = LU:mobileChangeGen(player,7)
    room:changeHero(player, general, false, false, true)
    room:handleAddLoseSkills(player,"-"..self.name,nil,false)
  end,
}
Fk:addSkill(mb_tthg)
Fk:loadTranslationTable{
  ["mb_tthg"] = "脱胎换骨",
  [":mb_tthg"] = "你可以变更武将",
}
--缮甲厉兵
local mb_sjlb = fk.CreateTriggerSkill{
  name = 'mb_sjlb',
  anim_type = "support",
  -- priority = 21,
  frequency = Skill.Compulsory,
  events = {fk.EventAcquireSkill},
  can_trigger = function(self, event, target, player, data)
    return player == target and data == self
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local searchnum = 2
    local totcount = 0
    local equipMap = {}
    local findequips = function(roompile,equipmap,count,num,needemptyslot)
      for _, id in ipairs(roompile) do
        local card = Fk:getCardById(id)
        local sub_type = card.sub_type
        if card.type == Card.TypeEquip and not table.contains(player.sealedSlots,Util.convertSubtypeAndEquipSlot(sub_type)) and (needemptyslot and (not player:getEquipment(sub_type)) or true) then
          local list = equipmap[tostring(sub_type)] or {}
          table.insert(list, id)
          equipmap[tostring(sub_type)] = list
          count = count + 1
          if count >= num then
            break
          end
        end
      end
    end
    findequips(room.draw_pile,equipMap,totcount,searchnum,true)
    if totcount < searchnum then
      findequips(room.discard_pile,equipMap,totcount,searchnum,false)
      if totcount < searchnum then
        local lastpile = #room.draw_pile > #room.discard_pile and room.draw_pile or room.discard_pile
        findequips(lastpile,equipMap,totcount,searchnum)
      end
    end
    local put = U.getRandomCards(equipMap, searchnum)
    if #put > 0 then
      U.moveCardIntoEquip(room, player, put, self.name, true, player)
    end
    room:handleAddLoseSkills(player,"-"..self.name,nil,false)
  end,
}
Fk:addSkill(mb_sjlb)
Fk:loadTranslationTable{
  ["mb_sjlb"] = "缮甲厉兵",
  [":mb_sjlb"] = "从牌堆置入2张装备（优先空栏位）",
}
--护卫
local mb_huwei = fk.CreateTriggerSkill{
  name = 'mb_huwei',
  anim_type = "defensive",
  priority = 5,
  -- frequency = Skill.Compulsory,
  events = {fk.TargetConfirmed},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and data.card.trueName == "slash" and data.to ~= player.id and data.from ~= player.id and #AimGroup:getAllTargets(data.tos) == 1 and player:distanceTo(player.room:getPlayerById(data.to)) == 1
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    return room:askForSkillInvoke(player, self.name, nil, "#huwei-invoke::"..data.to)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    data.tos = AimGroup:initAimGroup({})
    data.targetGroup = {}
    if U.canTransferTarget(player, data) then
      local targets = {player.id}
      if type(data.subTargets) == "table" then
        table.insertTable(targets, data.subTargets)
      end
      AimGroup:addTargets(room, data, targets)
    end
    return true
  end,
}
Fk:addSkill(mb_huwei)
Fk:loadTranslationTable{
  ["mb_huwei"] = "护卫",
  ["#huwei-invoke"] = "是否对%dest发动 护卫",
  [":mb_huwei"] = "你距离1的其他角色成为【杀】唯一目标时，若此【杀】来源不为你，你可以把目标转移给你。",
}
--飞矛
local mb_feimao = fk.CreateTriggerSkill{
  name = 'mb_feimao',
  anim_type = "offensive",
  priority = 6,
  -- frequency = Skill.Compulsory,
  events = {fk.TargetSpecifying},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and data.card.trueName == "slash" and player == target
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local discds = room:askForDiscard(player, 1, 1, false, self.name, true,".|.|.|.|.|trick");
    if discds and #discds > 0 then
      self.cost_data = discds
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local card = Fk:getCardById(self.cost_data[1])
    if card.type == Card.TypeTrick then
      data.disresponsiveList = data.disresponsiveList or {}
      table.insertIfNeed(data.disresponsiveList,data.to)
    end
  end,
}
Fk:addSkill(mb_feimao)
Fk:loadTranslationTable{
  ["mb_feimao"] = "飞矛",
  [":mb_feimao"] = "当你使用【杀】指定目标时，你可以弃1张锦囊牌，则目标不可被响应。",
}
--骑射
local mb_qishe = fk.CreateViewAsSkill{
  name = "mb_qishe",
  anim_type = "offensive",
  pattern = "slash",
  card_filter = function(self, to_select, selected)
    if #selected == 0 and Fk:getCardById(to_select).type == Card.TypeEquip then
      local c = Fk:cloneCard("slash")
      return (Fk.currentResponsePattern == nil and c.skill:canUse(Self, c)) or (Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(c))
    end
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then return end
    local c = Fk:cloneCard("slash")
    c.skillName = self.name
    c:addSubcards(cards)
    return c
  end,
}
local qishe_targetmod = fk.CreateTargetModSkill{
  name = "#qishe_targetmod",
  bypass_distances = function(self, player, skill, card)
    return player:hasSkill(mb_qishe) and skill.trueName == "slash_skill" and card and card.skillName == "mb_qishe"
  end,
}
mb_qishe:addRelatedSkill(qishe_targetmod)
Fk:addSkill(mb_qishe)
Fk:loadTranslationTable{
  ["mb_qishe"] = "骑射",
  ["#qishe_targetmod"] = "骑射",
  [":mb_qishe"] = "你可以将一张装备牌当【杀】使用或打出；你以此法使用的【杀】无距离限制。",
}

--战斗轮数
local battleTurn = #nextBattleData
--当前轮数
local curTurn = 1
--过滤其他卡组（只允许白名单的卡组加入牌堆）
local WHILEcards = {"standard","standard_cards","maneuvering","mobile_derived"}

local threembkj_getLogic = function()
  local threembkj_logic = GameLogic:subclass("threembkj_logic")

  function threembkj_logic:initialize(room)
    GameLogic.initialize(self, room)
    self.role_table = {
      { "lord" },
      { "lord", "rebel" },
      { "lord", "rebel", "rebel" },
      { "lord", "loyalist", "rebel", "rebel" },
      { "lord", "loyalist", "rebel", "rebel", "rebel" },
      { "loyalist", "loyalist", "loyalist", "loyalist", "rebel", "rebel" },
      { "lord", "rebel", "rebel", "rebel", "rebel", "rebel", "rebel" },
      { "lord", "loyalist", "loyalist", "rebel", "rebel", "rebel", "rebel", "loyalist" },
    }
    room.KJobj = KJobj:new({
      nextBattleData = nextBattleData,
      rebles = 3,
      maxplayers = 3,
      istest = IStest,
    })
  end

  function threembkj_logic:prepareForStart()
    self.room:setTag("@curturn",curTurn)
    self.room:setTag("@battleturn",battleTurn)
    self.room.KJobj:logic_prepareForStart({
      otherbanners = {{"@[:]threembkjbaner_rule","threembkj-intro"},{"@totalbattle",curTurn.."/"..math.max(1,battleTurn)},{"@seefriendcardstart",""}}
    })
  end

  function threembkj_logic:prepareDrawPile()
    self.room.KJobj:logic_prepareDrawPile({
      excepts = {},
      whitecards = WHILEcards
    })
  end

  function threembkj_logic:assignRoles()
    local room = Fk:currentRoom()
    local n = #room.players
    local bots,players = {},{}
    for i = 1, n do
      local p = room.players[i]
      if p.id < 0 then
        table.insert(bots,p)
      else
        table.insert(players,p)
      end
    end
    if #players < 3 then
      local subnum = 3 - #players
      for i = 1,subnum do
        table.insert(players,table.remove(bots))
      end
    end
    room.players = {}
    for i = 1, n do
      if i % 2 == 1 then
        room.players[i] = table.remove(players,math.random(1,#players))
      else 
        room.players[i] = table.remove(bots,1)
      end
    end

    local seecampcards = "loyalist"
    for i = 1, n do
      local p = room.players[i]
      p.role = i % 2 == 1 and "loyalist" or "rebel"
      p.role_shown = true
      room:broadcastProperty(p,"role")
    end
    for i = 1, n do
      local p = room.players[i]
      if seecampcards == p.role then
        for _,pr in ipairs(room.players) do
          if p ~= pr and seecampcards == pr.role then
            p:addBuddy(pr)
          end
        end
      end
    end
  end

  function threembkj_logic:chooseGenerals()
    local room = self.room
    room.current = room.players[1]

    MobileSelGenMuty:new({
      generalNum=12,
      repcount = 4,
      istest = IStest,
      openhobbygens = true,
      genpoolname = "MN_XLKJ",
    })
  end
  return threembkj_logic
end
---------------------------------------技能--------------------------------------------
local threembkj_rule = fk.CreateTriggerSkill{
  name = "#threembkj_rule",
  priority = 0.001,
  refresh_events = {fk.RoundStart,fk.BuryVictim,fk.GameStart,fk.GameOverJudge,fk.HpChanged,fk.Deathed},
  can_refresh = function(self, event, target, player, data)
    if event == fk.HpChanged then
      if player == target and player.room.seeskinman then
        local ret = player.room.KJobj:HpChangedEvt(player)
        if ret then
          self.cost_data = ret
          return true
        end
      end 
      return 
    end
    if event == fk.RoundStart or event == fk.GameStart then
      return player.seat == 1
    elseif event == fk.BuryVictim or event == fk.Deathed or event == fk.GameOverJudge then
      return player == target
    -- elseif event == fk.DrawNCards then
    --   return player == target and player.seat == 1 and player.room:getTag("RoundCount") == 1
    -- elseif event == fk.DrawInitialCards then
    --   return player == target and player.seat > 4
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.RoundStart then
      room.KJobj:roundStart()
    elseif event == fk.Deathed then
      room.KJobj:deaThed(data.who,true)
    elseif event == fk.BuryVictim then
      room.KJobj:buryVictim(data.who)
    elseif event == fk.GameOverJudge then
      room.KJobj:gameOverJudge()
      local drbySameCamp = function(ro)
        for _,pr in ipairs(room.alive_players) do
          if pr.role == ro then
            room:drawCards(pr,1,self.name)
          end
        end
      end
      drbySameCamp(player.role)
    elseif event == fk.GameStart then
      room.KJobj:gameStart()
    -- elseif event == fk.DrawNCards then
    --   data.n = data.n - 1
    -- elseif event == fk.DrawInitialCards then
    --   -- room.KJobj:drawInitialCards(data)
    --   data.num = data.num + (player.seat == 5 and 1 or 2)
    elseif event == fk.HpChanged then
      room.KJobj:changeSkin(player,self.cost_data)
    end
  end,
}
Fk:addSkill(threembkj_rule)

local threembkj_mode = fk.CreateGameMode{
  name = "threembkj_mode",
  minPlayer = 6,
  maxPlayer = 6,
  rule = threembkj_rule,
  logic = threembkj_getLogic,
  whitelist = table.clone(WHILEcards),
  winner_getter = function(self, victim)
    return ""
  end,
  surrender_func = function(self, playedTime)
    local surrenderJudge = { { text = "time limitation: 10s", passed = playedTime >= 10 } }
    -- if Self.role ~= "lord" then
      table.insert(surrenderJudge, { text = "1v1: left you alive", passed = true})
    -- end
    return surrenderJudge
  end,
}

Fk:loadTranslationTable{
  ["threembkj_mode"] = "手杀3v3抗人机",
  ["#threembkj_rule"] = "手杀3v3抗人机",
  ["@[:]threembkjbaner_rule"] = "手杀3v3",

  ["@seefriendcardstart"] = "点队友手牌数可看其手牌",
  

  ["threembkj-intro"]="点击介绍",
  [":threembkj-intro"]= desc_threembkj_mode,
  [":threembkj_mode"] = desc_threembkj_mode,
}

return threembkj_mode
